package data

import (
	"context"
	"fmt"
	"time"

	"user/internal/biz"

	"github.com/go-kratos/kratos/v2/log"
)

type userRepo struct {
	data *Data
	log  *log.Helper
}

func NewUserRepo(data *Data, logger log.Logger) biz.UserRepo {
	if data.dbEngine == nil {
		fmt.Println("------dbEngine为空---------")
		return nil
	}
	return &userRepo{
		data: data,
		log:  log.NewHelper(log.With(logger, "module", "data/user")),
	}
}

func (r *userRepo) CreateUser(ctx context.Context, u *biz.User) (*biz.User, error) {
	user := &User{
		Username:     u.Username,
		PasswordHash: u.PasswordHash,
		Status:       int32(u.Status),
	}

	if err := r.data.dbEngine.WithContext(ctx).Create(user).Error; err != nil {
		return nil, err
	}

	return &biz.User{
		ID:       user.ID,
		Username: user.Username,
	}, nil
}

func (r *userRepo) GetUser(ctx context.Context, id uint) (*biz.User, error) {
	var user User
	if err := r.data.dbEngine.WithContext(ctx).First(&user, id).Error; err != nil {
		return nil, err
	}

	return &biz.User{
		ID:        user.ID,
		Username:  user.Username,
		Status:    int32(user.Status),
		CreatedAt: user.CreatedAt.Format(time.RFC3339),
		UpdatedAt: user.UpdatedAt.Format(time.RFC3339),
	}, nil
}

func (r *userRepo) GetUserByUsername(ctx context.Context, username string) (*biz.User, error) {
	var user User
	if err := r.data.dbEngine.WithContext(ctx).Where("username = ?", username).First(&user).Error; err != nil {
		return nil, err
	}

	return &biz.User{
		ID:           user.ID,
		Username:     user.Username,
		PasswordHash: user.PasswordHash,
		Status:       int32(user.Status),
	}, nil
}
